package com.org.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.org.bean.common.DangerInfo;
import com.org.service.DangerService;

@Controller
@RequestMapping("/danger")
public class DangerAction {
	/**
	 * 险情信息初始化，数据采集及展示
	 */
	@Autowired
	private DangerService dangerService;
	private Iterator<String> iter;
	private List<String> list;

	private Map<String, Object> status(List<DangerInfo> dangerInfo) { // 封装成一个Json文件返回
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap<String, Object>();
		if (dangerInfo.size() != 0) {
			m.put("statusCode", 1);
			m.put("msg", "成功");
			m.put("result", dangerInfo);
		} else {
			m.put("statusCode", 0);
			m.put("msg", "失败");
		}
		return m;
	}

	private Map<String, Object> status(Boolean dangerInfo) {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap<String, Object>();
		if (dangerInfo) {
			m.put("statusCode", 1);
			m.put("msg", "成功");
		} else {
			m.put("statusCode", 0);
			m.put("msg", "失败");
		}
		return m;
	}

	@RequestMapping("/findAll")
	public @ResponseBody Map<String, Object> getDangerInfos() {
		List<DangerInfo> dangerInfo = new ArrayList<DangerInfo>();
		dangerInfo = dangerService.findAll();
		return status(dangerInfo);
	}
	
	@RequestMapping("/{dangerId}/findResult")
	public @ResponseBody Map<String, Object> getResult(@PathVariable int dangerId) {
		List<DangerInfo> dangerInfo = new ArrayList<DangerInfo>();
		dangerInfo = dangerService.findResult(dangerId);
		return status(dangerInfo);
	}

	@RequestMapping("{tunnelName}/{disasterName}/findByName")
	public @ResponseBody Map<String, Object> getDangerInfo(
			@PathVariable String tunnelName,@PathVariable String disasterName) {
		//System.out.println(tunnelName+disasterName);
		List<DangerInfo> dangerInfo = new ArrayList<DangerInfo>();
		dangerInfo = dangerService.findByName(tunnelName,disasterName);
		return status(dangerInfo);

	}

	@RequestMapping("/addDanger")
	public @ResponseBody Map<String, Object> addDanger(
			@RequestBody Map<String, Object> dangerMap) throws ParseException {
		boolean result;
		iter = dangerMap.keySet().iterator();
		list = new ArrayList<String>();
		while (iter.hasNext()) {
			list.add(iter.next());
		}
		DangerInfo dangerInfo = new DangerInfo();
		dangerInfo.setTunnelId((Integer) dangerMap.get(list.get(0)));
		dangerInfo.setDisasterId((Integer) dangerMap.get(list.get(1)));
		dangerInfo.setDangerName((String) dangerMap.get(list.get(2)));
		dangerInfo.setDescp((String) dangerMap.get(list.get(3)));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");           //将字符串转换为DATE类型
		Date date=sdf.parse((String) dangerMap.get(list.get(4)));
		dangerInfo.setOccurrenceTime(date);
		dangerInfo.setReportPerson((String) dangerMap.get(list.get(5)));
		dangerInfo.setContact((String) dangerMap.get(list.get(6)));
		result = dangerService.addDanger(dangerInfo);
		return status(result);
	}

	@RequestMapping("/updateDanger")
	public @ResponseBody Map<String, Object> updateDanger(
			@RequestBody Map<String, Object> dangerMap) throws ParseException {
		boolean result;
		iter = dangerMap.keySet().iterator(); // 获取Map集合的key值
		list = new ArrayList<String>();
		while (iter.hasNext()) {
			list.add(iter.next());
		}
		DangerInfo dangerInfo = new DangerInfo();
		dangerInfo.setDangerId((Integer) dangerMap.get(list.get(0)));
		dangerInfo.setTunnelId((Integer) dangerMap.get(list.get(1)));
		dangerInfo.setDisasterId((Integer) dangerMap.get(list.get(2)));
		dangerInfo.setDangerName((String) dangerMap.get(list.get(3)));
		dangerInfo.setDescp((String) dangerMap.get(list.get(4)));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");           //将字符串转换为DATE类型
		Date date=sdf.parse((String) dangerMap.get(list.get(5)));
		dangerInfo.setOccurrenceTime(date);
		dangerInfo.setReportPerson((String) dangerMap.get(list.get(6)));
		dangerInfo.setContact((String) dangerMap.get(list.get(7)));
		result = dangerService.updateDanger(dangerInfo);
		return status(result);
	}

	@RequestMapping("/{dangerId}/deleteDanger")
	public @ResponseBody Map<String, Object> deleteDanger(
			@PathVariable int dangerId) {
		boolean result;
		result = dangerService.deleteDanger(dangerId);
		return status(result);

	}
	
	/**
	 * 文件上传功能
	 * 
	 * @param req
	 * @param file
	 * @throws Exception
	 */
	@RequestMapping("/upload")
	public void fileupload(@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest req) throws IOException {
		int disasterId;
		String path = req.getSession().getServletContext()
				.getRealPath("/fileupload");
		disasterId = Integer.parseInt(req.getParameter("dangerId"));
		DangerInfo dangerInfo = new DangerInfo();
		dangerInfo.setDangerId(disasterId);
		dangerInfo.setTreatmentResult(file.getOriginalFilename());
		dangerService.updateResult(dangerInfo);
		InputStream is = file.getInputStream();
		OutputStream os = new FileOutputStream(new File(path,
				file.getOriginalFilename()));
		int len = 0;
		byte[] buffer = new byte[4000];
		while ((len = is.read(buffer)) != -1)
			os.write(buffer, 0, len);
		os.close();
		is.close();
	}

	/**
	 * 文件下载功能
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	@RequestMapping("/down")
	public void down(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 假如以中文名下载的话
		String filename = request.getParameter("treatmentResult");
		String fileName = request.getSession().getServletContext()
				.getRealPath("/fileupload")
				+ "/" + filename;
		// 获取输入流
		InputStream bis = new BufferedInputStream(new FileInputStream(new File(
				fileName)));

		// 转码，免得文件名中文乱码
		filename = URLEncoder.encode(filename, "UTF-8");
		// 设置文件下载头
		response.addHeader("Content-Disposition", "attachment;filename="
				+ filename);
		//设置文件ContentType类型，这样设置，会自动判断下载文件类型
		response.setContentType("multipart/form-data");
		BufferedOutputStream out = new BufferedOutputStream(
				response.getOutputStream());
		int len = 0;
		while ((len = bis.read()) != -1) {
			out.write(len);
			out.flush();
		}
		out.close();
	}

}
